<?php

    /**
     * Menu callback which provides the store administration overview page.
     */
    function tvn_admin_store() {
        module_load_include('inc', 'system', 'system.admin');
        $blocks = array();
        if ($admin = db_query("SELECT menu_name, mlid FROM {menu_links} WHERE link_path = 'admin/store' AND module = 'system'")->fetchAssoc()) {
            $result = db_query("
      SELECT m.*, ml.*
      FROM {menu_links} ml
      INNER JOIN {menu_router} m ON ml.router_path = m.path
      WHERE ml.link_path != 'admin/help' AND menu_name = :menu_name AND ml.plid = :mlid AND hidden = 0", $admin, array('fetch' => PDO::FETCH_ASSOC));
            foreach ($result as $item) {
                _menu_link_translate($item);
                if (!$item['access']) {
                    continue;
                }
                // The link 'description' either derived from the hook_menu 'description'
                // or entered by the user via menu module is saved as the title attribute.
                if (!empty($item['localized_options']['attributes']['title'])) {
                    $item['description'] = $item['localized_options']['attributes']['title'];
                }
                $block = $item;
                $block['content'] = theme('admin_block_content', array('content' => system_admin_menu_block($item)));
                if (!empty($block['content'])) {
                    $block['show'] = TRUE;
                }
                // Prepare for sorting as in function _menu_tree_check_access().
                // The weight is offset so it is always positive, with a uniform 5-digits.
                $blocks[(50000 + $item['weight']) . ' ' . $item['title'] . ' ' . $item['mlid']] = $block;
            }
        }
        ksort($blocks);
        $build['blocks'] = array(
            '#theme' => 'admin_page',
            '#blocks' => $blocks,
        );
        return $build;
    }

    /**
     * Displays main reports page.
     */
    function tvn_store_reports() {
        $menu = menu_get_item('admin/store/reports');
        $content = system_admin_menu_block($menu);
        $build['menu'] = array(
            '#theme' => 'admin_block_content',
            '#content' => $content,
            '#weight' => 5,
        );
        return $build;
    }

    /**
     * Displays store configuration page.
     */
    function tvn_store_configuration_page() {
        $menu = menu_get_item('admin/store/settings');
        $content = system_admin_menu_block($menu);
        $build['menu'] = array(
            '#theme' => 'admin_block_content',
            '#content' => $content,
        );
        return $build;
    }

    function tvn_store_address_setting_form($form, &$form_state) {
        $store_address = variable_get('wh_store_address');
        $form['#attached']['css'] = array(
            drupal_get_path('module', 'tvn_store') . '/css/tvn_store.css',
        );
        $form['address'] = array(
            '#type' => 'textfield',
            '#title' => t('Address'),
            '#required' => true,
            '#attributes' => array('placeholder' => t('Address')),
            '#maxlenght' => 128,
            '#default_value' => !empty($store_address->address) ? $store_address->address : '',
        );
        $form['city'] = array(
            '#type' => 'textfield',
            '#title' => t('City'),
            '#required' => true,
            '#attributes' => array('placeholder' => t('City')),
            '#maxlenght' => 128,
            '#default_value' => !empty($store_address->city) ? $store_address->city : '',
        );
        $form['state'] = array(
            '#type' => 'textfield',
            '#title' => t('State Name'),
            '#attributes' => array('placeholder' => t('State Name')),
            '#maxlenght' => 50,
            '#default_value' => !empty($store_address->state) ? $store_address->state : '',
        );
        $form['state_code'] = array(
            '#type' => 'textfield',
            '#title' => t('State Code'),
            '#attributes' => array('placeholder' => t('State Code')),
            '#maxlenght' => 50,
            '#default_value' => !empty($store_address->state_code) ? $store_address->state_code : '',
            '#suffix' => '<div style="clear: both;"></div>',
        );
        $options = function_exists('tvn_register_countries_array') ? tvn_register_countries_array() : array();
        $form['country'] = array(
            '#type' => 'select',
            '#title' => t('Country'),
            '#options' => $options,
            '#required' => true,
            '#default_value' => !empty($store_address->country) ? $store_address->country : '',
        );
        $form['zip'] = array(
            '#type' => 'textfield',
            '#title' => t('Zip'),
            '#required' => true,
            '#attributes' => array('placeholder' => t('Zip')),
            '#maxlenght' => 10,
            '#default_value' => !empty($store_address->zip) ? $store_address->zip : '',
        );
        $form['phone'] = array(
            '#type' => 'textfield',
            '#title' => t('Phone'),
            '#required' => true,
            '#attributes' => array('placeholder' => t('Phone')),
            '#maxlenght' => 15,
            '#default_value' => !empty($store_address->phone) ? $store_address->phone : '',
        );
        $form['phone_msg'] = array(
            '#type' => 'textarea',
            '#title' => t('Phone Message'),
            '#maxlenght' => 255,
            '#default_value' => !empty($store_address->phone_msg) ? $store_address->phone_msg : '',
        );
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save Configuration')
        );
        return $form;
    }

    function tvn_store_address_setting_form_submit($form, &$form_state) {
        $values = $form_state['values'];
        $address = (object) array(
            'address' => $values['address'],
            'city' => $values['city'],
            'state' => $values['state'],
            'state_code' => $values['state_code'],
            'country' => $values['country'],
            'zip' => $values['zip'],
            'phone' => $values['phone'],
            'phone_msg' => $values['phone_msg'],
        );
        variable_set('wh_store_address', $address);
        drupal_set_message(t('Configuration saved !'));
    }

    function tvn_store_shipping_services_settings($form, &$form_state) {
        $service_settings = variable_get('wh_services_settings', array());
        $form['#attached']['css'] = array(
            drupal_get_path('module', 'tvn_store') . '/css/tvn_store.css',
        );
        $form['services'] = array(
            '#tree' => TRUE,
        );
        $services = function_exists('tvn_calculator_shipping_services') ? tvn_calculator_shipping_services() : array();
        foreach ($services as $service => $s_val) {
            $form['services'][$service]['service_enabled'] = array(
                '#type' => 'checkbox',
                '#title' => $service,
                '#default_value' => isset($service_settings[$service]->status) ? $service_settings[$service]->status
                        : 0,
            );
            $form['services'][$service]['service_weight'] = array(
                '#type' => 'weight',
                '#default_value' => isset($service_settings[$service]->weight) ? $service_settings[$service]->weight
                        : 0,
                '#attributes' => array('class' => array('service-weight')),
            );
            $form['services'][$service]['operations'] = array(
                '#type' => 'link',
                '#href' => 'admin/store/settings/shipping_services/' . $service,
                '#title' => t('configure'),
            );
        }
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
        return $form;
    }

    function tvn_store_shipping_services_settings_submit($form, &$form_state) {
        $services = $form_state['values']['services'];
        $service_settings = array();
        foreach ($services as $service => $setting) {
            $service_settings[$service] = (object) array('status' => $setting['service_enabled'], 'weight' => $setting['service_weight']);
        }
        uasort($service_settings, 'tvn_store_sort_weight_obj');
        variable_set('wh_services_settings', $service_settings);
        drupal_set_message(t('Configuration saved!'));
    }

    function tvn_store_shipping_service_settings($form, &$form_state, $service) {
        $service_settings = variable_get('wh_service_settings', array());
        $services = function_exists('tvn_calculator_shipping_services') ? tvn_calculator_shipping_services() : array();
        if (isset($service) && in_array($service, array_keys($services))) {
            $form['service_setting'] = array(
                '#type' => 'vertical_tabs',
                '#tree' => true,
            );
            $form['service_setting']['credentials'] = array(
                '#type' => 'fieldset',
                '#title' => t('Credentials'),
                '#weight' => -99,
                '#description' => t('Set the conditions that will return a @service_name quote.', array('@service_name' => strtoupper($service)))
            );
            switch ($service) {
                case 'ups':
                    $form['service_setting']['credentials'][$service]['access_key'] = array(
                        '#type' => 'textfield',
                        '#title' => t('UPS OnLine Tools XML Access Key'),
                        '#required' => true,
                        '#default_value' => isset($service_settings[$service]->access_key)
                                ? $service_settings[$service]->access_key : '',
                    );
                    $form['service_setting']['credentials'][$service]['shipper'] = array(
                        '#type' => 'textfield',
                        '#title' => t('UPS Shipper #'),
                        '#required' => true,
                        '#description' => t('The 6-character string identifying your UPS account as a shipper.'),
                        '#default_value' => isset($service_settings[$service]->shipper)
                                ? $service_settings[$service]->shipper : '',
                    );
                    $form['service_setting']['credentials'][$service]['uid'] = array(
                        '#type' => 'textfield',
                        '#title' => t('UPS.com user ID'),
                        '#required' => true,
                        '#default_value' => isset($service_settings[$service]->uid) ? $service_settings[$service]->uid
                                : '',
                    );
                    $form['service_setting']['credentials'][$service]['pass'] = array(
                        '#type' => 'textfield',
                        '#title' => t('Password'),
                    );
                    break;
                case 'usps':
                    $form['service_setting']['credentials'][$service]['user_id'] = array(
                        '#type' => 'textfield',
                        '#title' => t('USPS user ID '),
                        '#required' => true,
                        '#description' => t('To acquire or locate your user ID, refer to the !link.', array('!link' => '<a href="http://drupal.org/node/1308256">USPS documentation</a>')),
                        '#default_value' => isset($service_settings[$service]->user_id)
                                ? $service_settings[$service]->user_id : '',
                    );
                    break;
                case 'fedex':
                    $form['service_setting']['credentials'][$service]['account'] = array(
                        '#type' => 'textfield',
                        '#title' => t('Fedex Account'),
                        '#required' => true,
                        '#default_value' => isset($service_settings[$service]->account)
                                ? $service_settings[$service]->account : '',
                    );
                    $form['service_setting']['credentials'][$service]['meter'] = array(
                        '#type' => 'textfield',
                        '#title' => t('Fedex Meter'),
                        '#required' => true,
                        '#default_value' => isset($service_settings[$service]->meter)
                                ? $service_settings[$service]->meter : '',
                    );
                    break;
            }
            $form['service_setting']['service_options'] = array(
                '#type' => 'fieldset',
                '#title' => t('Service Options'),
                '#weight' => -98,
            );
            $form['service_setting']['service_options']['options'] = array(
                '#type' => 'checkboxes',
                '#title' => t('@service_name Services', array('@service_name' => strtoupper($service))),
                '#options' => isset($services[$service]) ? $services[$service] : array(),
                '#default_value' => isset($service_settings[$service]->options) ? $service_settings[$service]->options
                        : array(),
            );
            $form['service_setting']['service_name'] = array(
                '#type' => 'value',
                '#value' => !empty($service) ? $service : '',
            );
            if ($service == 'ups') {
                // Fields for default package size (inches)
                $form['service_setting']['default_package_size'] = array(
                    '#type' => 'fieldset',
                    '#title' => t('Package size (inches)'),
                    '#description' => 'UPS requires a package size when determining estimates.',
                );
                $form['service_setting']['default_package_size']['wh_ups_default_package_size_length'] = array(
                    '#type' => 'textfield',
                    '#title' => t('Length'),
                    '#size' => 5,
                    '#required' => TRUE,
                    '#default_value' => variable_get('wh_ups_default_package_size_length'),
                );
                $form['service_setting']['default_package_size']['wh_ups_default_package_size_width'] = array(
                    '#type' => 'textfield',
                    '#title' => t('Width'),
                    '#size' => 5,
                    '#required' => TRUE,
                    '#default_value' => variable_get('wh_ups_default_package_size_width'),
                );
                $form['service_setting']['default_package_size']['wh_ups_default_package_size_height'] = array(
                    '#type' => 'textfield',
                    '#title' => t('Height'),
                    '#size' => 5,
                    '#required' => TRUE,
                    '#default_value' => variable_get('wh_ups_default_package_size_height'),
                );
                $form['service_setting']['default_package_size']['details'] = array(
                    '#markup' => 'The package size is used to determine the number of packages necessary to
                      create a UPS shipping cost estimate. <strong>If products do not have physical dimensions and
                      weights associated with them, the estimates will not be accurate.</strong> The logic implemented works as:
                      <ul>
                      <li>Assume each order requires at least one package.</li>
                      <li>Use the combined volume of all products in an order to determine the number of packages.</li>
                      </ul>
                      This is a simple calculation that can get close to actual shipping costs. More
                      complex logic involving multiple package sizes, weights, and void space can be implemented via
                      custom modules.
                      <br/><br/>
                      UPS has a ' . l('maximum package size', 'http://www.ups.com/content/us/en/resources/prepare/oversize.html', array('attributes' => array('target' => '_blank'))) . '.',
                );
            }
            $form['actions'] = array('#type' => 'actions');
            $form['actions']['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Save configuration')
            );
        }
        return $form;
    }

    function tvn_store_shipping_service_settings_submit($form, &$form_state) {
        $service_settings = variable_get('wh_service_settings', array());
        $values = $form_state['values']['service_setting'];
        if (!empty($values['service_name'])) {
            if ($values['service_name'] == 'ups' && $values['credentials']['ups']['pass'] == '') {
                $values['credentials']['ups']['pass'] = !empty($service_settings['ups']->pass)
                        ? $service_settings['ups']->pass : '';
            }
            $settings = $values['credentials'][$values['service_name']];
            $settings['options'] = array();
            foreach ($values['service_options']['options'] as $k => $v) {
                if ($v) {
                    $settings['options'][] = $k;
                }
            }
            $service_settings[$values['service_name']] = (object) $settings;
            variable_set('wh_service_settings', $service_settings);
            foreach ($values['default_package_size'] as $key => $val) {
                variable_set($key, $val);
            }
        }
        drupal_set_message(t('Configuration saved!'));
    }

    function theme_tvn_store_shipping_services_settings($variables) {
        $form = $variables['form'];
        drupal_add_tabledrag('wh-shipping-services', 'order', 'sibling', 'service-weight');
        $header = array(array('data' => t('Shipping service'), 'colspan' => 2), t('Operations'));
        $rows = array();
        foreach (element_children($form['services']) as $service) {
            $row = array(
                drupal_render($form['services'][$service]['service_enabled']),
                drupal_render($form['services'][$service]['service_weight']),
                drupal_render($form['services'][$service]['operations']),
            );
            $rows[] = array(
                'data' => $row,
                'class' => array('draggable'),
                'weight' => $form['services'][$service]['service_weight']['#default_value'],
            );
        }
        uasort($rows, 'tvn_store_sort_weight_arr');
        $output = theme('table', array(
                                      'header' => $header,
                                      'rows' => $rows,
                                      'attributes' => array('id' => 'wh-shipping-services'),
                                      'empty' => t('No shipping quotes have been configured yet.'),
                                 ));
        $output .= drupal_render_children($form);
        return $output;
    }

    function tvn_store_standard_services_setting_form($form, &$form_state) {
        $services_fees = variable_get('wh_standard_services_fees', array());
        $services_op = variable_get('wh_optional_services_fees', array());
        $form['#attached']['css'] = array(
            drupal_get_path('module', 'tvn_store') . '/css/tvn_store.css',
        );
        $form['settings'] = array(
            '#type' => 'vertical_tabs',
        );
        $form['settings']['standard'] = array(
            '#type' => 'fieldset',
            '#title' => t('Standard Services'),
            '#tree' => true,
            '#weight' => -99,
        );
        $form['settings']['standard']['in_shipment_fee'] = array(
            '#type' => 'textfield',
            '#title' => t('Incoming Shipment Fee'),
            '#field_prefix' => '$',
            '#default_value' => !empty($services_fees->in_shipment_fee) ? $services_fees->in_shipment_fee : '0',
        );
        $form['settings']['standard']['mediation_fee'] = array(
            '#type' => 'textfield',
            '#title' => t('Mediation Fee per incident'),
            '#field_prefix' => '$',
            '#default_value' => !empty($services_fees->mediation_fee) ? $services_fees->mediation_fee : '0',
        );
        $form['settings']['standard']['storage_fee'] = array(
            '#type' => 'fieldset',
            '#title' => t('Storage Fee'),
        );
        $form['settings']['standard']['storage_fee']['fee'] = array(
            '#type' => 'textfield',
            '#title' => t('Storage Fee per item per week'),
            '#field_prefix' => '$',
            '#default_value' => !empty($services_fees->storage_fee['fee']) ? $services_fees->storage_fee['fee'] : '0',
        );
        $form['settings']['standard']['storage_fee']['day_exp'] = array(
            '#type' => 'textfield',
            '#title' => t('Free after days'),
            '#default_value' => !empty($services_fees->storage_fee['day_exp']) ? $services_fees->storage_fee['day_exp']
                    : '30',
        );
        $form['settings']['optional'] = array(
            '#type' => 'fieldset',
            '#weight' => -98,
            '#title' => t('Optional Services')
        );
        $form['settings']['optional']['services'] = array(
            '#type' => 'wrapper',
            '#tree' => true,
            '#prefix' => '<div id="optional_services_wrapper">',
            '#suffix' => '</div>',
        );
        if (!isset($form_state['num_setting'])) {
            $form_state['num_setting'] = !empty($services_op) ? count($services_op) : 1;
        }
        for ($i = 0; $i < $form_state['num_setting']; $i++) {
            $form['settings']['optional']['services'][$i]['service'] = array(
                '#type' => 'textfield',
                '#title' => t('Service Name'),
                '#default_value' => !empty($services_op[$i]) ? $services_op[$i]->service : '',
                '#prefix' => '<div class="item-border">'
            );
            $form['settings']['optional']['services'][$i]['fee'] = array(
                '#type' => 'textfield',
                '#title' => t('Service Fee'),
                '#field_prefix' => '$ or %',
                '#default_value' => !empty($services_op[$i]) ? $services_op[$i]->fee : '0',
                '#suffix' => '</div>',
            );
        }
        $form['settings']['optional']['add_more'] = array(
            '#type' => 'submit',
            '#value' => t('Add more service'),
            '#submit' => array('tvn_store_optional_service_add_more_submit'),
            '#ajax' => array(
                'callback' => 'tvn_store_optional_service_add_more_callback',
                'wrapper' => 'optional_services_wrapper',
                'method' => 'replace',
                'effect' => 'fade',
            ),
        );
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Save configuration'),
        );
        return $form;
    }

    function tvn_store_standard_services_setting_form_submit($form, &$form_state) {
        $setting = array();
        $setting_op = array();
        foreach ($form_state['values']['standard'] as $key => $val) {
            if ($key == 'storage_fee') {
                $val = array('fee' => ($val['fee'] ? $val['fee'] : '0'), 'day_exp' => ($val['day_exp'] ? $val['day_exp']
                        : 30)
                );
            }
            if (empty($val) && $key != 'storage_fee') {
                $val = 0;
            }
            $setting[$key] = $val;
        }
        variable_set('wh_standard_services_fees', (object) $setting);
        foreach ($form_state['values']['services'] as $val) {
            if ($val['service']) {
                $fee = $val['fee'];
                if (strpos($val['fee'], '%' === false)) {
                    $fee = $val['fee'] . '$';
                }
                $setting_op[] = (object) array(
                    'service' => $val['service'],
                    'fee' => $fee,
                );
            }
        }
        variable_set('wh_optional_services_fees', $setting_op);
        drupal_set_message(t('Configuration saved.'));
    }

    function tvn_store_optional_service_add_more_submit($form, &$form_state) {
        $form_state['num_setting']++;
        $form_state['rebuild'] = true;
    }

    function tvn_store_optional_service_add_more_callback($form, &$form_state) {
        return $form['settings']['optional']['services'];
    }

    function tvn_store_shelf_setting_form($form, &$form_state) {
        $form['setting'] = array(
            '#type' => 'fieldset',
            '#title' => t('Shelf setting.')
        );
        $form['setting']['item_per_shelf'] = array(
            '#type' => 'textfield',
            '#title' => t('Number items per Shelf'),
            '#required' => true,
            '#default_value' => variable_get('item_per_shelf', ''),
        );
        return system_settings_form($form);
    }